/**
 * 提供所有与字符串操作相关的公用函数
 * 
 * @author javen
 * @author allen
 * 
 * @version $Revision: 1.1 $ $Date: 2010/05/04 10:50:11 $
 */
package cn.org.timespace.easyframe.util;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.util.LabelValueBean;

import sun.misc.BASE64Decoder;

public class StringUtils2 {
	public static String getNewtheNO(int theID) {
		String number = "";
		number = DateUtils2.getNowDate().toString();
		number = number.substring(0, 4) + number.substring(5, 7)
				+ number.substring(8, 10);
		if (theID == 1
				|| StringUtils.substringAfter((theID + ""), number) == "") {

			number = number + "01";
		} else {
			number = theID + "";

		}
		return number;
	}

	public static String replaceNewLine(final String in) {
		if (in == null) {
			return null;
		}
		char ch;
		char[] input = in.toCharArray();
		int len = input.length;
		final StringBuffer out = new StringBuffer((int) (len * 1.3));
		for (int index = 0; index < len; index++) {
			ch = input[index];
			if (ch == '\n') {
				out.append("<br>");
			} else if (ch == ' ') {
				out.append("&nbsp;");
			} else {
				out.append(ch);
			}

		}
		return out.toString();
	}

	public static String transferGb2312(String in) {
		String out = null;
		try {
			byte[] ins = in.getBytes("iso-8859-1");
			out = new String(ins, "GBK");
		} catch (Exception e) {
		}
		return out;
	}

	public static String transferGb23121(String in) {
		String out = null;
		try {
			byte[] ins = in.getBytes("iso-8859-1");
			out = new String(ins, "gb2312");
		} catch (Exception e) {
		}
		return out;
	}

	public static String transferISO8859(String in) {
		String out = null;
		try {
			byte[] ins = in.getBytes("gb2312");
			out = new String(ins, "iso-8859-1");
		} catch (Exception e) {
		}
		return out;
	}

	public static String transferutf8(String in) {
		String out = null;
		try {
			byte[] ins = in.getBytes("iso-8859-1");
			out = new String(ins, "UTF-8");
		} catch (Exception e) {
		}
		return out;
	}

	public static String transferutf8ISO8859(String in) {
		String out = null;
		try {
			byte[] ins = in.getBytes("UTF-8");
			out = new String(ins, "iso-8859-1");
		} catch (Exception e) {
		}
		return out;
	}

	/**
	 * 返回指定长度的字符串，如果原字符串长度超过指定长度，则只返回原字符串的前 面的字符，并且在后面加“...”
	 * 
	 * @param str
	 *            源字符串
	 * 
	 * @param length
	 *            要返回的指定长度
	 * 
	 * @return 返回指定长度的字符串
	 */
	public static String getShortString(String str, int length) {
		String result;

		if (str.length() > length) {
			result = str.substring(0, length) + "....";
		} else {
			result = str;
		}
		return result;
	}

	/**
	 * 接受分页中文
	 * 
	 * @param in
	 * @return
	 */
	public static String convertIso8859ToGb2312(String in) {
		String out = null;
		try {
			byte[] ins = in.getBytes("iso-8859-1");
			out = new String(ins, "utf-8");
		} catch (Exception e) {
		}
		return out;
	}

	public static String convertGb2312ToIso8859(String in) {
		String out = null;
		try {
			byte[] ins = in.getBytes("gb2312");
			out = new String(ins, "iso-8859-1");
		} catch (Exception e) {
		}
		return out;
	}

	public static String createRandomString() {
		String random = null;
		// 产生随机字符串
		random = RandomStringUtils.randomAlphabetic(10);
		// 随机字符串再加上当前的日期时间 long
		random += DateUtils2.getNowDateTimeLong();
		return random;
	}

	/**
	 * 如果传入的字符串为null，则转换为""，如果不是null,则返回字符串trim()后的值， 即截去两头空格后的字符串
	 * 
	 * @param str
	 *            传入的字符串
	 * 
	 * @return 经过处理后的字符串
	 */
	public static String convertNullToString(String str) {

		if (str == null) {
			return "";
		} else {
			return str.trim();
		}
	}

	/**
	 * 根据传入的各个字段(QueryField类对象)，获得查询语句的条件部分，包括WHERE
	 * 
	 * @param list
	 *            多个QueryField类对象的列表
	 * 
	 * @return 查询语句的条件部分，即WHERE子句，包括WHERE。 如果list为空或list中的内容都不合条件，返回空字符串""。
	 */
	// public static String getQueryStringIncludeWhere(List list) {
	//
	// String rtn = getQueryStringBarringWhere(list);
	//
	// if (!rtn.trim().equals(""))
	// rtn = " WHERE " + rtn;
	//
	// return rtn;
	// }
	/**
	 * 根据传入的各个字段(QueryField类对象)，获得查询语句的条件部分，不包括WHERE
	 * 
	 * @param list
	 *            多个QueryField类对象的列表
	 * 
	 * @return 查询语句的条件部分，即WHERE子句，但不包括WHERE。 如果list为空或list中的内容都不合条件，返回空字符串""。
	 */
	// public static String getQueryStringBarringWhere(List list) {
	// String rtn = "";
	// String temp = "";
	// QueryField qf;
	//
	// //如果查询条件为空，则直接返回""
	// if ((list == null) || list.size() == 0)
	// return "";
	//
	// //获得初步查询语句
	// for (int i = 0; i < list.size(); i++) {
	// try {
	// qf = (QueryField) list.get(i);
	// if (qf != null)
	// temp += qf.getTypeQueryString();
	// } catch (Exception e) {
	// }
	// }
	//
	// temp = temp.trim();
	//
	// //去掉最后的AND/OR，并加上( )
	// if (temp.length() > 0) {
	// int lastPoint = temp.length();
	// if (temp.endsWith("AND"))
	// lastPoint = temp.lastIndexOf("AND");
	// else if (temp.endsWith("OR"))
	// lastPoint = temp.lastIndexOf("OR");
	//
	// rtn = temp.substring(0, lastPoint);
	// }
	// return rtn;
	// }
	public static boolean checkEmailIsValid(String email) {
		boolean isok = false;
		if (email.equals("") || email == "" || email == null)
			isok = false;
		for (int i = 1; i < email.length(); i++) {
			char s = email.charAt(i);
			if (s == '@')
				isok = true;
		}
		return isok;
	}

	public static String showText(String str, int type) {

		if (str == null)
			return "";

		if (type == 0) {
		} else if (type == 1) {
			// 禁止html输出
			str = replace(str, "&", "&amp;");
			str = replace(str, "<", "&lt;");
			str = replace(str, ">", "&gt;");
			str = replace(str, " ", "&nbsp;");
			str = replace(str, "\n", "<br>");
		} else if (type == 2) {
			// 显示html, 可以html输出
			str = replace(str, "  ", "&nbsp;&nbsp;");
			str = replace(str, "\n", "<br>");
		} else if (type == 3) {
			// 在表单内显示
		} else if (type == 4) {
			// 禁止html，显示ubb
			str = replace(str, "&", "&amp;");
			str = replace(str, "<", "&lt;");
			str = replace(str, ">", "&gt;");
			str = replace(str, "  ", "&nbsp;&nbsp;");
			str = replace(str, "\n", "<br/>");
		} else if (type == 5) {
			str = replace(str, "&amp;", "&");
			str = replace(str, "&lt;", "<");
			str = replace(str, "&gt;", ">");
			str = replace(str, "&nbsp;", " ");
			str = replace(str, "<br/>", "<\n>");

		} else {
		}
		return str;
	}

	/**
	 * 字符串替换函数
	 * 
	 * @param str
	 *            原字符串
	 * @param pattern
	 *            要替换的字符串
	 * @param replace
	 *            替换的值
	 * @return
	 */
	public static String replace(String str, String pattern, String replace) {

		if (replace == null) {
			replace = "";
		}
		int s = 0, e = 0;

		/* 建立StringBuffer对象 */
		StringBuffer result = new StringBuffer((int) str.length() * 2);
		while ((e = str.indexOf(pattern, s)) >= 0) {
			result.append(str.substring(s, e));
			result.append(replace);
			s = e + pattern.length();
		}
		result.append(str.substring(s));
		return result.toString();
	}

	/**
	 * 判断是否为数字
	 * 
	 */
	public static boolean isNumber(String str) {
		String sStr = "";
		int m = 0;
		m = str.indexOf(".");

		for (int j = 0; j < str.length(); j++) {
			if (m != j)
				sStr = sStr + str.charAt(j);
		}

		byte[] btyeStr = sStr.getBytes();
		for (int i = 0; i < btyeStr.length; i++) {
			if ((btyeStr[i] < 48) || (btyeStr[i] > 57)) {
				return false;
			}
		}
		return true;
	}

	public static String getFromBASE64(String s) {
		s = s + "=";

		if (s == null)
			return null;
		BASE64Decoder decoder = new BASE64Decoder();

		try {
			byte[] b = decoder.decodeBuffer(s);

			return new String(b);

		} catch (Exception e) {
			return null;
		}
	}

	public static String toChinese(String strvalue) {
		try {
			if (strvalue == null)
				return null;
			else {
				strvalue = new String(strvalue.getBytes("ISO8859-1"), "UTF-8");
				return strvalue;
			}
		} catch (Exception e) {
			return null;
		}
	}

	public static String toXmlString2(List items) {
		String encoding = "utf-8";
		StringBuffer xml = new StringBuffer().append("<?xml version=\"1.0\"");
		if (encoding != null) {
			xml.append(" encoding=\"");
			xml.append(encoding);
			xml.append("\"");
		}
		xml.append(" ?>\r\n");

		xml.append("<root>\r\n");
		xml.append("<response>\r\n");
		for (Iterator iter = items.iterator(); iter.hasNext();) {
			LabelValueBean item = (LabelValueBean) iter.next();
			xml.append("<item>\r\n");
			xml.append("<text>\r\n");
			xml.append("<![CDATA[");
			xml.append(item.getLabel());
			xml.append("]]>");
			xml.append("</text>\r\n");
			xml.append("<value>\r\n");
			xml.append("<![CDATA[");
			xml.append(item.getValue().trim());
			xml.append("]]>");
			xml.append("</value>\r\n");
			xml.append("</item>\r\n");
		}
		xml.append("</response>\r\n");
		xml.append("</root>");
		return xml.toString();

	}

	/**
	 * 模糊查询构造字符串 特定格式:
	 * 
	 * @param listtemp
	 * @return
	 */
	public static String getStringByList(List listtemp) {
		String ajaxString = "";
		for (int i = 0; i < listtemp.size(); i++) {
			LabelValueBean item = (LabelValueBean) listtemp.get(i);
			String[] name = item.getLabel().split("_");
			ajaxString += item.getValue() + "###" + name[0] + "|";
		}
		return ajaxString;
	}

	/**
	 * 判斷日期如果是單位數字，則在前面加0
	 */

	public static String addZero(String day) {
		try {
			if (day == null)
				return null;
			else {
				int num = day.length();
				if (num == 1) {
					return "0" + day;
				} else {
					return day;
				}
			}
		} catch (Exception e) {
			return null;
		}
	}

	public static Object arrayGrow(Object obj, int addLength) {
		Class clazz = obj.getClass();
		if (!clazz.isArray()) {
			return null;
		}
		Class componentType = clazz.getComponentType();
		int length = Array.getLength(obj);
		int newLength = length + addLength;
		Object newArray = Array.newInstance(componentType, newLength);
		System.arraycopy(obj, 0, newArray, 0, length);
		return newArray;
	}

	/**
	 * 将汉字转换为全拼
	 * 
	 * @param src
	 * @return String
	 */
	public static String getPinYin(String src) {
		char[] t1 = null;
		t1 = src.toCharArray();
		// System.out.println(t1.length);
		String[] t2 = new String[t1.length];
		// System.out.println(t2.length);
		// 设置汉字拼音输出的格式
		HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
		t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		t3.setVCharType(HanyuPinyinVCharType.WITH_V);
		String t4 = "";
		int t0 = t1.length;
		try {
			for (int i = 0; i < t0; i++) {
				// 判断是否为汉字字符
				// System.out.println(t1[i]);
				if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
					t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);// 将汉字的几种全拼都存到t2数组中
					t4 += t2[0];// 取出该汉字全拼的第一种读音并连接到字符串t4后
				} else {
					// 如果不是汉字字符，直接取出字符并连接到字符串t4后
					t4 += Character.toString(t1[i]);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return t4;
	}

	public static String convertUTFToGBK(String in) {
		String out = null;
		try {
			byte[] ins = in.getBytes("UTF-8");
			out = new String(ins, "GBK");
		} catch (Exception e) {
		}
		return out;
	}

	public static String enUnicode(String content) {// 将汉字转换为16进制数
		String enUnicode = null;
		for (int i = 0; i < content.length(); i++) {
			if (i == 0) {
				enUnicode = getHexString(Integer.toHexString(content.charAt(i))
						.toUpperCase());
			} else {
				enUnicode = enUnicode
						+ getHexString(Integer.toHexString(content.charAt(i))
								.toUpperCase());
			}
		}
		return enUnicode;
	}

	private static String getHexString(String hexString) {
		String hexStr = "";
		for (int i = hexString.length(); i < 4; i++) {
			if (i == hexString.length())
				hexStr = "0";
			else
				hexStr = hexStr + "0";
		}
		return hexStr + hexString;
	}

	public static void main(String[] args) {
		System.out.println(StringUtils2.convertUTFToGBK("爸爸"));
		System.out.println(enUnicode(StringUtils2.transferGb23121("爸爸")));
		try {
			System.out.println(enUnicode(new String("爸爸".toString().getBytes(
					"GBK"), "utf-16")));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/** 计算时间毫秒 */
	private static long fromDateStringToLong(Date inVal) {
		Date date = null; // 定义时间类型
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			String dateStr = format.format(inVal);
			date = format.parse(dateStr); // 将字符型转换成日期型
		} catch (Exception e) {
			e.printStackTrace();
		}
		return date.getTime(); // 返回毫秒数
	}
	
	
	public static final int sent_type_day = 0;
	public static final int sent_type_hours = 1;
	public static final int sent_type_minutes = 2;
	public static final int sent_type_seconds = 3;
	/**
	 * 计算时间差      当前时间  - 结束时间
	 * @param Date startDate notNull 当前时间
	 * @param Date endDate   notNull 结束时间
	 * @param int  sentType  notNull 返回值类型(天/小时/分钟/秒)
	 * @param sentType = StringUtils2.sent_type_day
	 * @param sentType = StringUtils2.sent_type_hours
	 * @param sentType = StringUtils2.sent_type_minutes
	 * @param sentType = StringUtils2.sent_type_seconds
	 * */
	public static long dateToSent(Date startDate, Date endDate,int sentType) {
		long startT = fromDateStringToLong(startDate); // 开始时间
		long endT = fromDateStringToLong(endDate); // 结束时间
		long second=(startT-endT)/(1000); //共计秒数 
	    long min = second/60;   //共计分钟数
	    long hour = min/60; //共计小时数
	    long day = hour/24;   //共计天数
	    long lon=0;
	    switch (sentType) {
		case 0:
			lon = day;
			break;
		case 1:
			lon = hour;
			break;
		case 2:
			lon = min;	
			break;
		case 3:
			lon = second;
			break;
		}
		return lon;
	}
}
